package com.byit.solr;

import com.byit.utils.DateUtil;
import lombok.Data;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;

import java.util.*;

/**
 * solr返回参数封装
 *
 * @author tjm
 * @date 2019/1/15.
 */
@Data
public class SolrResult{

    private Long current;
    private Long pages;
    private Long total;
    private Integer size;
    private List<Map<String,Object>> records;

    private SolrResult(QueryResponse queryResponse, Integer limit,String hight){
        if (queryResponse != null){
            SolrDocumentList results = queryResponse.getResults();
            // 数量，分页用
            long total = results.getNumFound();
            List<Map<String,Object>> result = new ArrayList<>();
            // 获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
            Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting();
            results.forEach(o -> {
                if (o.containsKey("createTime")){
                    String date = o.get("createTime").toString();
                    if (date.contains(".")){
                        o.put("createTime",date.substring(0,date.lastIndexOf(":")));
                    }else {
                        try {
                            o.put("createTime",DateUtil.dateFormat(new Date(date), "yyyy-MM-dd HH:mm"));
                        }catch (Exception e){
                            o.put("createTime","未知");
                        }
                    }
                }
                Map<String,Object> data = new HashMap<>();
                data.putAll(o);
                data.put("highlight",highlight.get(o.get("id").toString()).get(hight).get(0));
                result.add(data);
            });
            this.current = results.getStart()+1;
            this.pages = total/limit+(total%limit == 0 ? 0 : 1 );
            this.total = total;
            this.size = limit;
            this.records = result;
        }
    }
    public static SolrResult result(QueryResponse queryResponse,Integer limit,String hight){
        return new SolrResult(queryResponse,limit,hight);
    }

}
